<CFSET sDate1 = DATEFORMAT(Now(),"mm/dd/yyyy")>

<CFSET sReRoute = FALSE>
<CFSET sCurrentSequence = 0>

<!--- ******************************************************************* --->
<!--- ******************************************************************* --->
<!--- *********	  THIS IS THE ROUTING PROCESS                  ********** --->
<!--- *********   STARTS HERE....                              ********** --->
<!--- ******************************************************************* --->
<!--- ******************************************************************* --->

<CFSET FIRST=TRUE>
<CFIF ISDEFINED("Form.CHKACTION")>
	<CFLOOP LIST="#Form.CHKACTION#" index="i">
		<CFIF sWarn EQ "">
			<CFQUERY NAME="checkEntry" DATASOURCE="#table_dsn#">
				SELECT APPROVED, ROUTEID FROM #GetForm.TABLENAME_FK#
				WHERE
					(PERSONNELIDNO = '#GetEmployee.PERSONNELIDNO#'
					<CFLOOP LIST="#i#" index="d" delimiters="~">
							AND #preservesinglequotes(d)#
					</CFLOOP>
					)
			</CFQUERY>
			<CFIF checkEntry.APPROVED NEQ "" AND checkEntry.APPROVED NEQ "R" AND (checkEntry.ROUTEID NEQ "" AND checkEntry.APPROVED NEQ 'N')>
				<CFTHROW type = "ROUTE" message = "Operation aborted." detail = "Record has already been routed. This maybe due to reloading the page after routing a record.">
			<CFELSE>
				<CFIF checkEntry.APPROVED EQ "R" OR checkEntry.APPROVED EQ "B">
					<CFSET sReRoute = TRUE>
				</CFIF>
			</CFIF>
			<CFTRY>
				<!--- get the activity code involved (first record)--->
				<CFQUERY NAME="GetInvAct" DATASOURCE="#client.company_dsn#">
					SELECT ACTIVITYID, MAPPING, ROLECODE, UNITCODE
					FROM CINFFACTIVITY
					WHERE
					<CFIF ISDEFINED("CLIENT.newformflow")>
						(PROCESSCODE = '#CLIENT.newformflow#')
					<CFELSE>
						(PROCESSCODE = '#GetForm.PROCESSCODE#')
					</CFIF>
					ORDER BY ORDERID
				</CFQUERY>
				<!--- If Form is re-routed or not (from returned to originator)... - winston--->
				<CFIF sReRoute IS FALSE>
					<CFSET sRouteID = #CreateUUID()#>
					<CFSET sCurrentSequence = 1>
					<CFSET sStarted = "STARTED">
					<CFSET sInitialization = "INITIALIZATION">
				<CFELSE>
					<CFSET sMess = "Re-Route.<BR>">
					<CFSET sRouteID = checkEntry.ROUTEID>
					<CFQUERY NAME="checkCurrSequence" DATASOURCE="#client.company_dsn#">
						SELECT MAX(CURRENTSEQUENCE) AS CURRENTSEQUENCE
						FROM CRGROUTEDETAILS
						WHERE (ROUTEID = '#sRouteID#')
					</CFQUERY>
					<CFSET sCurrentSequence = checkCurrSequence.CURRENTSEQUENCE + 1>
					<CFSET sStarted = "RE-ROUTE">
					<CFSET sInitialization = "#GetInvAct.ACTIVITYID#">
				</CFIF>

				<!--- update the record itself --->
				<!-- Added by Mhel --->
				<!--- Start --->
				<CFINCLUDE TEMPLATE="_saveoverride.cfm">
				<!--- End --->

				<!--- Modified by Soti 05/25/2004
					 Checking of newly routed forms field APPROVED value used to be NULL,
					 changed to 'S' for Submitted for compatibility to BOS/e Personnel Movements
					 because it does not accept NULL values.
					 For iBOS/e APPROVED values are:
					 1. Y for approved
					 2. N for disapproved
					 3. B for back to sender/last approver	- Winston
					 4. R for returned
					 5. S for submitted --->

				<!--- log to detail router --->
				<CFQUERY NAME="SaveRouteDetail" DATASOURCE="#client.company_dsn#">
					INSERT
					INTO CRGROUTEDETAILS
						(ROUTEID, ORDERID, CURRENTSEQUENCE, ROUTER, ROUTERREMARKS, STATUS, ACTIVITYID,
						RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
					VALUES
						('#sRouteID#', 1, '#sCurrentSequence#', '#client.userid#', '', '#sStarted#', '#sInitialization#',
						'#client.userid#',
						'#preserveSingleQuotes(sDate1)#',
						'#client.userid#',
						'#preserveSingleQuotes(sDate1)#',
						'#TIMEFORMAT(Now(), "hh:mmtt")#')
				</CFQUERY>
				<CFIF sReRoute IS FALSE>
					<!--- log to master router --->
					<CFQUERY NAME="SaveRouteMaster" DATASOURCE="#client.company_dsn#">
						INSERT
						INTO CRGROUTEMAIN
							(ROUTEID, DESCRIPTION, TABLENAME_FK,
							ORIGINATOR, PRIORITY, ORGENTITY, INCLUDEEFORM, ROUTEPARAMS,
							RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
						VALUES
							('#sRouteID#', '#GetForm.DESCRIPTION#', '#GetForm.TABLENAME_FK#',
							'#client.userid#', '#Form.cmbPriority#', '#client.orgent#', '#form.rdoIncludeForm#',
							'levelid="#GetLevelID.LEVELID#"|subcompanycode="#client.subcompany_code#"',
							'#client.userid#', '#preserveSingleQuotes(sDate1)#',
							'#client.userid#', '#preserveSingleQuotes(sDate1)#',
							'#TIMEFORMAT(Now(), "hh:mmtt")#')
					</CFQUERY>
				</CFIF>
				<!---ADDED BY JEP, TO REMOVE FROM WORKLIST--->
				<CFIF sReRoute>
					<CFQUERY NAME="SaveRouteDetail" DATASOURCE="#client.company_dsn#">
						UPDATE CRGROUTERECORDS
						SET ISHIDE='Y'
						WHERE ISHIDE='N'
							AND ROUTEID='#sRouteID#'
					</CFQUERY>
				</CFIF>
				<!---ENDS HERE--->
				<CFQUERY NAME="SaveRouteRec" DATASOURCE="#table_dsn#">
					UPDATE #GetForm.TABLENAME_FK#
						SET
							ROUTEID = '#sRouteID#',
							APPROVED = 'S'
						WHERE
							PERSONNELIDNO = '#GetEmployee.PERSONNELIDNO#'
							<CFLOOP LIST="#i#" index="d" delimiters="~">
									AND #preservesinglequotes(d)#
							</CFLOOP>

				</CFQUERY>



				<!--- trap errors --->
				<CFCATCH>
					<CFSET sWarn = #CFCATCH.message# & #CFCATCH.DETAIL#>
				</CFCATCH>
			</CFTRY>

			<CFTRY>
				<!--- initilize mail and msg variables --->
				<CFSET sMailRecipients = "">
				<CFSET sRecordID = CreateUUID()>
				<CFSET sMsgRecipients = "">
				<CFSET sIntendedRecipient="">
				<CFSET sPerSuperior = "">

				<CFSWITCH EXPRESSION="#lcase(GetInvAct.MAPPING)#">

					<!--------------------------------------->
					<!--- the originator is the recipient --->
					<!--------------------------------------->
					<CFCASE VALUE="originator">
						<!--- this cannot be, it is invalid! --->
						<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" MODULE="#session.tabId#" LOCATION="#session.tabLocation#" COMPONENT="Error in form-flow process">
						<BR><BR>
						<H3>Invalid mapping.</H3>
						<CFOUTPUT>
						Originator to Originator mapping is not allowed.
						Please notify your iBOS/e Administrator.
						</CFOUTPUT>
						<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" TOP="False">
						<CFABORT>
					</CFCASE>

					<!-------------------------------------------------->
					<!--- extract the recipient through the unitcode --->
					<!-------------------------------------------------->
					<CFCASE VALUE="userrole">
						<!--- get intended recipients --->
						<CFQUERY NAME="GetRecipients" DATASOURCE="#client.global_dsn#">
							SELECT USERGRPMEMBERSIDX, GUID FROM EGRGROLEINDEX, EGRGUSERMASTER
							WHERE
								EGRGUSERMASTER.USERID = EGRGROLEINDEX.USERGRPMEMBERSIDX AND
								USERGRPID_FK = '#GetInvAct.ROLECODE#';
						</CFQUERY>

						<!--- if sole individual in role, SIYA NA! --->
						<CFIF GetRecipients.RecordCount EQ 1>
							<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#GetRecipients.USERGRPMEMBERSIDX#">
							<CFIF ISFOUND>
								<!--- log to route records --->
								<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
									INSERT
									INTO CRGROUTERECORDS
										(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
										PROCESSCODE, ACTIVITYID, ROUTEID,
										ISNEW, ISHIDE, RECORDID,
										RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
									VALUES
										('#GetRecipients.USERGRPMEMBERSIDX#',
										'#preserveSingleQuotes(sDate1)#',
										'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
										'#GetForm.PROCESSCODE#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
										'Y','N', '#sRecordID#',
										'#client.userid#',
										'#preserveSingleQuotes(sDate1)#',
										'#client.userid#',
										'#preserveSingleQuotes(sDate1)#',
										'#TIMEFORMAT(Now(), "hh:mmtt")#')
								</CFQUERY>

								<CFSET sMsgRecipients  = sMsgRecipients  & "(" & PERID & ") " & PERNAME & ", ">
								<CFSET sMailRecipients=PERADDRESS>
								<CFSET sIntendedRecipient=GetRecipients.USERGRPMEMBERSIDX>
							</CFIF>	<!--- recipient is valid --->
						<CFELSE>
							<!--- set unitcode to use --->
							<CFSET sUnitCode2Use=Trim(GetInvAct.UNITCODE)>
							<CFIF sUnitCode2Use IS "">
								<CFSET sUnitCode2Use="UNITCODE">
							</CFIF>

							<!--- get the userid that override members in userrole --->
							<CFQUERY NAME="overridemapping" DATASOURCE="#client.company_dsn#">
								SELECT *
								FROM ECMFUSRDEFINEROLE
								WHERE ROUTEID = '#sRouteID#' AND
									  ACTIVITYID = '#GetInvAct.ACTIVITYID#'
							</CFQUERY>
							<CFSET sCode2Use=Trim(overridemapping.USERID)>

							<CFLOOP QUERY="GetRecipients">
								<CFIF sCode2Use IS "">
									<!--- in case overriding of members in userrole is not
										done by the user before routing the form,
										mapping will re-route to any member of the
										userrole with same unitcode as of the originator --->
									<CFQUERY NAME="GetEntity" DATASOURCE="#client.company_dsn#">
										SELECT #sUnitCode2Use#
										FROM CMFPA
										WHERE GUID = '#GetRecipients.GUID#'
									</CFQUERY>
									<CFSET lContinue="Yes">
								<CFELSEIF sCode2Use IS GetRecipients.USERGRPMEMBERSIDX>
									<CFSET lContinue="Yes">
								<CFELSE>
									<CFSET lContinue="No">
								</CFIF>

								<CFIF lContinue>
									<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#GetRecipients.USERGRPMEMBERSIDX#">
									<CFIF ISFOUND>
										<!--- in case overriding of members in userrole is not
											done by the user before routing the form,
											mapping will re-route to any member of the
											userrole with same unitcode as of the originator --->
										<CFIF sCode2Use IS "">
											<CFQUERY NAME="getdivision" DATASOURCE="#client.company_dsn#">
												SELECT #sUnitCode2Use#
												FROM CMFPA
												WHERE PERSONNELIDNO = '#client.chapa#'
											</CFQUERY>
										</CFIF>

										<CFIF (sCode2Use IS NOT "") OR
											  (
												GetEntity.RecordCount AND
												getdivision.RecordCount AND
												ucase(Evaluate("GetEntity." & sUnitCode2Use)) EQ
												ucase(Evaluate("getdivision." & sUnitCode2Use))
											  )
										>
											<!--- log to route records --->
											<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
												INSERT
												INTO CRGROUTERECORDS
													(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
													PROCESSCODE, ACTIVITYID, ROUTEID,
													ISNEW, ISHIDE, RECORDID,
													RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
												VALUES
													('#GetRecipients.USERGRPMEMBERSIDX#',
													'#preserveSingleQuotes(sDate1)#',
													'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
													'#GetForm.PROCESSCODE#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
													'Y','N', '#sRecordID#',
													'#client.userid#',
													'#preserveSingleQuotes(sDate1)#',
													'#client.userid#',
													'#preserveSingleQuotes(sDate1)#',
													'#TIMEFORMAT(Now(), "hh:mmtt")#')
											</CFQUERY>

											<CFSET sIntendedRecipient=GetRecipients.USERGRPMEMBERSIDX>
											<CFSET sMsgRecipients  = sMsgRecipients  & "(" & PERID & ") " & PERNAME & ", ">
											<CFSET sMailRecipients=PERADDRESS>
										</CFIF>	<!--- unitcode of originator is the same with the recipient --->
									</CFIF>	<!--- recipient is validated --->
								</CFIF>
							</CFLOOP>
						</CFIF>
					</CFCASE>

					<!----------------------------------------------->
					<!--- the immediate superior is the recipient --->
					<!----------------------------------------------->
					<CFDEFAULTCASE> <!--- superior --->
						<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#client.userid#">
						<CFIF ISFOUND>
							<CFIF Trim(PERSUPERIOR) NEQ "">
								<CFQUERY NAME="GetCode" DATASOURCE="#client.company_dsn#">
									SELECT GUID, PERSONNELIDNO, LASTNAME #sqlCONCAT# ', ' #sqlCONCAT# FIRSTNAME #sqlCONCAT# ' ' #sqlCONCAT# MIDDLENAME AS NAME
									FROM CMFPA
									WHERE PERSONNELIDNO = '#PERSUPERIOR#'
								</CFQUERY>

								<CFIF GetCode.RecordCount>
									<!--- extract profile name --->
									<CFQUERY NAME="GetProfileName" DATASOURCE="#client.global_dsn#">
										SELECT USERID, PROFILENAME
										FROM EGRGUSERMASTER
										WHERE GUID = '#GetCode.GUID#'
									</CFQUERY>

									<CFIF GetProfileName.RecordCount>
										<CFSET sIntendedRecipient=GetProfileName.USERID>
										<!--- log to route records --->
										<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
											INSERT
											INTO CRGROUTERECORDS
												(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
												PROCESSCODE, ACTIVITYID, ROUTEID,
												ISNEW, ISHIDE, RECORDID,
												RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
											VALUES
												('#GetProfileName.USERID#',
												'#preserveSingleQuotes(sDate1)#',
												'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
												'#GetForm.PROCESSCODE#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
												'Y','N', '#sRecordID#',
												'#client.userid#',
												'#preserveSingleQuotes(sDate1)#',
												'#client.userid#',
												'#preserveSingleQuotes(sDate1)#',
												'#TIMEFORMAT(Now(), "hh:mmtt")#')
										</CFQUERY>

										<CFSET sIntendedRecipient=GetProfileName.USERID>
										<CFSET sMailRecipients=Trim(GetProfileName.PROFILENAME)>
										<CFSET sMsgRecipients = sMsgRecipients  & "(" & GetCode.PERSONNELIDNO & ") " & GetCode.NAME>
									<CFELSE>
										<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="SUPERIORNOIBOSE">
									</CFIF> <!--- profile not found --->
								<CFELSE>
									<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="SUPERIORNOTEXIST">
								</CFIF> <!--- Approving party's superior doesn't exist in CMFPA --->
							<CFELSE>
								<CFSET sPerSuperior = "">
								<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="NOSUPERIOR">
							</CFIF> <!--- Approving party doesn't have superior --->
						</CFIF>
					</CFDEFAULTCASE>
				</CFSWITCH>
				<!--- ************************************************************* --->
				<!--- ************************************************************* --->
				<!--- ******    THE ROUTING PATH IS DEFINED AND EXTRACTED   ******* --->
				<!--- ******    THE PROCESS ENDS HERE                       ******* --->
				<!--- ************************************************************* --->
				<!--- ************************************************************* --->

				<CFIF sIntendedRecipient IS "">
					<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" MODULE="#session.tabId#" LOCATION="#session.tabLocation#" COMPONENT="Error in form-flow process">
					<BR><BR>
					<H3>Intended Recipient is missing.</H3>
					Please notify your iBOS/e Administrator.
					<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" TOP="False">
					<CFABORT>
				</CFIF>

				<!--- get the process of eform for eform follow-up and forwarding --->
				<CFQUERY NAME="qryCINFFPROCESS" DATASOURCE="#client.company_dsn#">
					SELECT ISFOLLOW, FOLLOWHOURS, ISFORWARD, FORWARDHOURS
					FROM CINFFPROCESS
					WHERE (PROCESSCODE = '#GetForm.PROCESSCODE#')
				</CFQUERY>

				<CFIF UCase(qryCINFFPROCESS.ISFOLLOW) IS "Y" AND qryCINFFPROCESS.FOLLOWHOURS GT 0>
					<CFSET lFollowUp=true>
				<CFELSE>
					<CFSET lFollowUp=false>
				</CFIF>
				<CFIF UCase(qryCINFFPROCESS.ISFORWARD) IS "Y" AND qryCINFFPROCESS.FORWARDHOURS GT 0>
					<CFSET lForward=true>
				<CFELSE>
					<CFSET lForward=false>
				</CFIF>

				<!--- set variables for followup or forwarding --->
				<CFIF lFollowUp OR lForward>
					<!--- remove http:// in parameters --->
					<CFIF LCase(Left(client.mailtransporturl, 7)) IS "http://">
						<CFSET sMailTransportURL=Mid(client.mailtransporturl, 8, Len(client.mailtransporturl))>
					<CFELSE>
						<CFSET sMailTransportURL=client.mailtransporturl>
					</CFIF>
					<CFSET sMailTransportURL=URLEncodedFormat(sMailTransportURL)>
				</CFIF>

				<!--- create schedule for follow-up --->
				<!--- Start --->
				<CFIF lFollowUp AND sMailRecipients IS NOT "">
					<CFSET sURL=client.domain & "schedule/followmail.cfm?mailtransporturl=" & sMailTransportURL &
							"&mailserver=" & URLEncodedFormat(client.mailserver) &
							"&mailbox=" & URLEncodedFormat(client.mailbox) &
							"&userid=" & URLEncodedFormat(sIntendedRecipient) &
							"&mailcontent=" & URLEncodedFormat(client.mailcontent) &
							"&sender=" & URLEncodedFormat(client.myname) &
							"&urldomain=" & "#client.domain#" &
							"&url3=" & URLEncodedFormat(client.companycode) &
							"&url4=" & URLEncodedFormat(sRecordID) &
							"&from=" & URLEncodedFormat(LCase(client.profilename)) &
							"&to=" & URLEncodedFormat(LCase(sMailRecipients)) &
							"&dsn=" & client.company_dsn &
							"&ek=" & URLEncodedFormat(client.ek) &
							"&compname=" & URLEncodedFormat(client.companyname) &
							"&formgroup=" & URLEncodedFormat(GetForm.formgroup) &
							"&formdescription=" & URLEncodedFormat(GetForm.description)>
					<CFIF lForward>
						<CFSET sURL=sURL & "&forward=" & qryCINFFPROCESS.FORWARDHOURS>
					<CFELSE>
						<CFSET sURL=sURL & "&followup=" & qryCINFFPROCESS.FOLLOWHOURS>
					</CFIF>

					<CFSET nFollowHours = qryCINFFPROCESS.FOLLOWHOURS * 60>
					<CFSCHEDULE ACTION="Update"
						TASK="follow#sRecordID#"
						OPERATION="HTTPRequest"
						STARTDATE="#Now()#"
						STARTTIME="#TimeFormat(DateAdd('n', qryCINFFPROCESS.FOLLOWHOURS, Now()))#"
						URL="#sURL#"
						INTERVAL="#nFollowHours#">
				</CFIF>
				<!--- End --->

				<!--- create schedule for forwarding --->
				<!--- Start --->
				<CFIF lForward>
					<!--- get recipients alternate approver --->
					<CFMODULE TEMPLATE="#client.common_path#routing/routefunc_getalternate.cfm"
						USERID="#sIntendedRecipient#">

					<CFIF ALTERNATE NEQ "">
						<!--- Create alternate approver schedule --->
						<CF_IBOSELOG MODULE="EFORMS:UPDATE&ROUTE" LEVEL="INFORMATION" FILE="_saverouteMAPISMTP.cfm"
							MESSAGE="Created schedule for alternate approver: USERID=#sIntendedRecipient#, ALTERNATE=#ALTERNATE#.">
						<CFMODULE TEMPLATE="#client.common_path#routing/routefunc_createsched.cfm"
							MAILTRANSPORTURL = "#sMailTransportURL#"
							USERID = "#sIntendedRecipient#"
							RECORDID = "#sRecordID#"
							PROCESSID = "#GetForm.PROCESSCODE#"
							ACTIVITYID = "#GetInvAct.ACTIVITYID#"
							ROUTEID = "#sRouteID#"
							TABLE_DSN = "#table_dsn#"
							TABLENAME = "#GetForm.TABLENAME_FK#"
							FORMGROUP = "#GetForm.formgroup#"
							FORMDESC = "#GetForm.description#"
							FORWARDHOURS = "#qryCINFFPROCESS.FORWARDHOURS#"
							ALTAPPROVER = "#ALTERNATE#"
							ALTAPPROVERCOUNT = "1"
							ORIGAPPROVER = "#sIntendedRecipient#"
							COMPNAME="#client.companyname#"
							>
					</CFIF>
				</CFIF>
				<!--- End --->

				<!--- trap errors --->
				<CFCATCH>
					<CFSET sWarn = #CFCATCH.message# & #CFCATCH.DETAIL#>
				</CFCATCH>
			</CFTRY>
			<CFIF SESSION.TABID EQ "movements">
				<CFSET session.sMess = "Form routing successfully delivered.<BR>">
				<CFLOCATION url="#client.domain#emovements/index.cfm">

			</CFIF>
		</CFIF>
	</CFLOOP>
	<CFSET sMess = sMess & "Form routing successfully initialized.<BR>">

<CFELSE>
	<CFSET sWarn= "You must at select least one record to proceed">
</CFIF>
